﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using LogFileScanner.Properties;
using System.Media;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

using WeifenLuo.WinFormsUI.Docking;

namespace LogFileScanner
{
    public partial class ScanViewer : DockContent, LogFileScanner.Viewer
    {
        private ListViewColumnSorter listMatchedFilesColumnSorter = new ListViewColumnSorter();
        
        public ScanViewer()
        {
            InitializeComponent();
            listMatchedFiles.ListViewItemSorter = listMatchedFilesColumnSorter;
            setDateFillterType();

            LoadDefaultSettings();

        }

        #region Public Interface

        public event Utility.VoidMethodDelegate NotifyProgressStart;
        public event Utility.VoidMethodDelegate NotifyProgressStop;
        public event Utility.MessageMethodDelegate NotifyLogMessage;

        public delegate void FileListLoaded(IList<FileInfo> fileList);
        public event FileListLoaded NotifyFileListLoaded;
        
        public delegate void FileLoaded(FileInfo file);
        public event FileLoaded NotifyOpenStream;

        public event Utility.VoidMethodDelegate NotifyOpenGrep;

        public void Terminate()
        {
            backgroundWorkerScan.CancelAsync();
        }

        #endregion

        #region Event Callback

        private void processStart()
        {
            if (NotifyProgressStart != null)
            {
                NotifyProgressStart();
            }
        }

        private void processStop()
        {
            if (NotifyProgressStop != null)
            {
                NotifyProgressStop();
            }
        }


        private void logMessage(string value, Utility.MessageLevel level)
        {
            if (NotifyLogMessage != null)
            {
                NotifyLogMessage(value, level);
            }
        }

        #endregion 

        #region Settings IO
        
        private Settings AppSettings { 
            get { return Settings.Default; } 
        }
        
        private void UpdateDefaultSettings() {
            try {
                /*
                string pathsString = textPaths.Text;
                string[] paths = pathsString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                AppSettings.DefaultPaths.Clear();
                foreach (string path in paths)
                {
                    AppSettings.DefaultPaths.Add(path);
                }

                AppSettings.FileFilter = comboFileFitler.Text;
                AppSettings.FileFilterDate = dateTimeFromFilter.Value;
                */

                if (AppSettings.RecentFileFilters == null)
                {
                    AppSettings.RecentFileFilters = new System.Collections.Specialized.StringCollection();
                }
                else
                {
                    AppSettings.RecentFileFilters.Clear();
                }

                foreach (object recentFileFitler in comboFileFitler.Items) 
                {
                    if (recentFileFitler is string)
                    {
                        AppSettings.RecentFileFilters.Add(recentFileFitler as string);
                    }
                }

                AppSettings.Save();
                
                if (comboBoxRecentSearch.SelectedItem != null)
                {
                    ScanSetting setting = comboBoxRecentSearch.SelectedItem as ScanSetting;
                    setting.Store();
                }

                /*
                foreach (ScanSetting setting in comboBoxRecentSearch.Items)
                {
                    setting.Store();
                }
                 */

            }
            catch (Exception ex)
            {
                logMessage(string.Format("Unable to save default settings due to {0}.", ex.Message), Utility.MessageLevel.WARN);
            }
        }
        
        private void LoadDefaultSettings() {
            try
            {
                if (string.IsNullOrEmpty(Settings.Default.SettingsPath))
                {
                    Settings.Default.SettingsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                }

                /*
                string pathsString = "";

                if (AppSettings.DefaultPaths != null)
                {

                    foreach (string path in AppSettings.DefaultPaths)
                    {
                        if (string.IsNullOrEmpty(pathsString))
                        {
                            pathsString += path;
                        }
                        else
                        {
                            pathsString += Environment.NewLine + path;
                        }
                    }
                }
                textPaths.Text = pathsString;
                comboFileFitler.Text = AppSettings.FileFilter;
                */

                comboBoxRecentSearch.Items.Clear();

                string settingsPath = Path.GetFullPath(Settings.Default.SettingsPath);
                if (Directory.Exists(settingsPath))
                {
                    string[] files = Directory.GetFiles(settingsPath, "*.scan");
                    foreach (string file in files)
                    {
                        string fileName = Path.GetFileNameWithoutExtension(file);
                        ScanSetting scanInput = new ScanSetting(fileName);
                        comboBoxRecentSearch.Items.Add(scanInput);
                    }
                }

                foreach (ScanSetting setting in comboBoxRecentSearch.Items)
                {
                    if (setting.Name == "Default")
                    {
                        comboBoxRecentSearch.SelectedItem = setting;
                    }
                }

                if (!isSettingLoaded() && comboBoxRecentSearch.Items.Count > 0)
                {
                    ScanSetting setting = comboBoxRecentSearch.Items[0] as ScanSetting;
                    comboBoxRecentSearch.SelectedItem = setting;
                }

                if (AppSettings.RecentFileFilters != null)
                {
                    comboFileFitler.Items.Clear();
                    foreach (string recentFileFitler in AppSettings.RecentFileFilters)
                    {
                        comboFileFitler.Items.Add(recentFileFitler);
                    }
                }
            }
            catch (Exception ex)
            {
                logMessage(string.Format("Unable to load default settings due to {0}.", ex.Message), Utility.MessageLevel.WARN);
            }
        }

        private void StoreScanSetting(ScanSetting scanSetting)
        {
            try
            {
                string pathsString = textPaths.Text;
                string[] paths = pathsString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                if (!string.IsNullOrEmpty(comboBoxRecentSearch.Text))
                {
                    scanSetting.Name = comboBoxRecentSearch.Text;
                }
                scanSetting.FileFilter = comboFileFitler.Text;
                if (dateTimeFromFilter.Checked)
                {
                    scanSetting.FilterFromDate = dateTimeFromFilter.Value;
                }
                else
                {
                    scanSetting.FilterFromDate = DateTime.MinValue;
                }
                if (dateTimeToFilter.Checked)
                {
                    scanSetting.FilterToDate = dateTimeToFilter.Value;
                }
                else
                {
                    scanSetting.FilterToDate = DateTime.MinValue;
                }

                scanSetting.Paths = paths;
                scanSetting.Store();

                comboBoxRecentSearch.Items.Remove(scanSetting);
                comboBoxRecentSearch.Items.Add(scanSetting);
                comboBoxRecentSearch.SelectedItem = scanSetting;

                NotifyLogMessage(string.Format("The Scan Setting '{0}' was saved to {1}", scanSetting.Name, scanSetting.FilePath), Utility.MessageLevel.INFO);
            }
            catch (Exception ex)
            {
                NotifyLogMessage("Unable to save the scan settings: " + ex.Message, Utility.MessageLevel.ERROR);
            }
        }


        private bool isSettingLoaded()
        {
            return comboBoxRecentSearch.SelectedItem != null;
        }

        #endregion

        #region Background Worker Scan

        private void backgroundWorkerScan_DoWork(object sender, DoWorkEventArgs e)
        {
            processStart();

            Nullable<DateTime> searchFromTime = getFilterFromDate();
            Nullable<DateTime> searchToTime = getFilterToDate();
            string searchFileFilter = getFitlerFile();
            
            string pathsString = textPaths.Text;
            string[] paths = pathsString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            if (paths.Length == 0)
            {
                logMessage("Canceled, no search paths detected", Utility.MessageLevel.WARN);
                return;
            }

            bool hasInvalidDirectories = false;

            foreach (string path in paths)
            {
                if (backgroundWorkerScan.CancellationPending)
                {
                    logMessage("Canceling the scan at user's request", Utility.MessageLevel.WARN);
                    return;
                }

                string foundPath = path.Trim();

                if (Directory.Exists(foundPath))
                {
                    logMessage(string.Format("Searching for {0} in path {0}", searchFileFilter, foundPath), Utility.MessageLevel.INFO);

                    DirectoryInfo directory = new DirectoryInfo(foundPath);

                    FileInfo[] files = directory.GetFiles(searchFileFilter, SearchOption.TopDirectoryOnly);
                    logMessage(string.Format("Found {0} files in the path: {1}, filtering by date...", files.Length, foundPath), Utility.MessageLevel.INFO);

                    if (searchFromTime.HasValue)
                    {
                        DateTime from_date = searchFromTime.Value;
                        DateTime to_date;
                        if (searchToTime.HasValue)
                        {
                            to_date = searchToTime.Value;
                        }
                        else
                        {
                            to_date = from_date.AddHours(Math.Abs(AppSettings.DateRangeHours));
                        }
                        IEnumerable<FileInfo> filteredFiles = files.Where(file => (file.CreationTime >= from_date || file.LastWriteTime >= from_date) && (file.CreationTime <= to_date || file.LastWriteTime <= to_date));

                        if (searchToTime.HasValue)
                        {
                            foreach (FileInfo file in filteredFiles)
                            {
                                addFileToList(file);
                            }
                        } 
                        else 
                        {
                            FileInfo foundLogFile = null;
                            DateTime foundLogFileDate = DateTime.MaxValue;

                            if (filteredFiles.Count() == 0)
                            {
                                from_date = from_date.AddHours(-1);
                                filteredFiles = files.Where(file => file.LastWriteTime > from_date && file.LastWriteTime <= to_date);

                            }

                            foreach (FileInfo file in filteredFiles)
                            {
                                if (file.LastWriteTime < foundLogFileDate)
                                {
                                    foundLogFileDate = file.LastWriteTime;
                                    foundLogFile = file;
                                }
                            }

                            addFileToList(foundLogFile);
                        }
                    }
                    else
                    {
                        foreach (FileInfo file in files)
                        {
                            addFileToList(file);
                        }
                    }
                }
                else
                {
                    logMessage(string.Format("Directory {0} is not found", foundPath), Utility.MessageLevel.WARN);
                    hasInvalidDirectories = true;
                }
            }

            if (hasInvalidDirectories)
            {
                logMessage("Scan finished, some paths were not valid.", Utility.MessageLevel.WARN); 
            }
            else
            {
                logMessage("Scan finished.", Utility.MessageLevel.INFO);
            }
        }

        private void backgroundWorkerScan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            processStop();

            IList<FileInfo> files = new List<FileInfo>();

            foreach (ListViewItem listItem in listMatchedFiles.Items)
            {
                string filePath = listItem.SubItems[1].Text;
                FileInfo file = new FileInfo(filePath);
                files.Add(file);
            }

            if (NotifyFileListLoaded != null)
            {
                NotifyFileListLoaded(files);
            }
            
            buttonScan.Text = "&Scan";
            buttonScan.Enabled = true;
        }

        #endregion 

        #region Internal Callbacks

        private delegate void fileInfoMethodDelegate(FileInfo file);
        private delegate Nullable<DateTime> returnDateMethodDelegate();
        private delegate string returnStringMethodDelegate();


        private void addFileToList(FileInfo file)
        {
            if (InvokeRequired) { Invoke((fileInfoMethodDelegate)addFileToList, file); return; }

            if (file == null)
            {
                return;
            }

            ListViewItem item = new ListViewItem(file.Name);
            item.SubItems.Add(file.FullName);
            item.SubItems.Add(file.LastWriteTime.ToString());
            item.SubItems.Add(file.CreationTime.ToString());
            item.SubItems.Add(Utility.FormatFileSize(file.Length));
            listMatchedFiles.Items.Add(item);
        }

        private Nullable<DateTime> getFilterFromDate()
        {
            if (InvokeRequired) { return (Nullable<DateTime>)Invoke((returnDateMethodDelegate)getFilterFromDate); }

            if (dateTimeFromFilter.Checked)
            {
                return dateTimeFromFilter.Value;
            }
            else
            {
                return null;
            }
        }

        private Nullable<DateTime> getFilterToDate()
        {
            if (InvokeRequired) { return (Nullable<DateTime>)Invoke((returnDateMethodDelegate)getFilterToDate); }

            if (dateTimeToFilter.Checked)
            {
                return dateTimeToFilter.Value;
            }
            else
            {
                return null;
            }
        }

        private string getFitlerFile()
        {
            if (InvokeRequired) { return (string)Invoke((returnStringMethodDelegate)getFitlerFile); }

            if (comboFileFitler.Text != null)
            {
                return comboFileFitler.Text;
            }
            else
            {
                return "*";
            }
        }

        #endregion

        #region Helper Methods

        private void OpenGrepWindow()
        {
            IList<FileInfo> files = new List<FileInfo>();

            if (listMatchedFiles.SelectedItems.Count > 0)
            {
                foreach (ListViewItem listItem in listMatchedFiles.SelectedItems)
                {
                    string filePath = listItem.SubItems[1].Text;
                    FileInfo file = new FileInfo(filePath);
                    files.Add(file);
                }
            }
            else
            {
                foreach (ListViewItem listItem in listMatchedFiles.Items)
                {
                    string filePath = listItem.SubItems[1].Text;
                    FileInfo file = new FileInfo(filePath);
                    files.Add(file);
                }
            }

            if (NotifyFileListLoaded != null) {
                NotifyFileListLoaded(files);
            }

            if (NotifyOpenGrep != null) {
                NotifyOpenGrep();
            }
        }

        private void OpenExternalEditor()
        {
            // for each file, open either extenral editor
            foreach (ListViewItem listItem in listMatchedFiles.SelectedItems)
            {
                OpenExternalEditor(listItem);
            }
        }

        private void OpenFolder()
        {
            // for each file, open either extenral editor
            foreach (ListViewItem listItem in listMatchedFiles.SelectedItems)
            {
                OpenFolder(listItem);
            }
        }
        
        private void OpenExternalEditor(ListViewItem listItem)
        {
            string fileName = listItem.SubItems[0].Text;
            string filePath = listItem.SubItems[1].Text;

            string commandLineArguments = string.Format(AppSettings.EditorArguments, filePath);

            try
            {
                System.Diagnostics.Process.Start(AppSettings.EditorPath, commandLineArguments);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Unable to open file {0}.\n\tUnable to start \"{1}\"\n\tWith arguments: {2}.\n\tCause: {3}",
                                fileName, AppSettings.EditorPath, commandLineArguments, ex.Message));
            }
        }

        private void OpenFolder(ListViewItem listItem)
        {
            string fileName = listItem.SubItems[0].Text;
            string filePath = listItem.SubItems[1].Text;

            string commandLineArguments = string.Format(AppSettings.ExplorerArguments, filePath);

            try
            {
                System.Diagnostics.Process.Start(AppSettings.ExplorerPath, commandLineArguments);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Unable to open file {0}.\n\tUnable to start \"{1}\"\n\tWith arguments: {2}.\n\tCause: {3}",
                                fileName, AppSettings.EditorPath, commandLineArguments, ex.Message));
            }
        }
        private void OpenStream()
        {
            // for each file, open internal editor
            foreach (ListViewItem listItem in listMatchedFiles.SelectedItems)
            {
                OpenStream(listItem);
            }
        }

        private void OpenStream(ListViewItem listItem)
        {
            if (NotifyOpenStream != null)
            {
                string fileName = listItem.SubItems[0].Text;
                string filePath = listItem.SubItems[1].Text;

                FileInfo file = new FileInfo(filePath);
                NotifyOpenStream(file);
            }
            else
            {
                MessageBox.Show("Unable to open the stream, no steam listeners avaialble.");
            }
        }

        private void setDateFillterType()
        {
            if (dateTimeFromFilter.Checked)
            {
                dateTimeToFilter.Enabled = true;
                if (dateTimeToFilter.Checked)
                {
                    labelFromDate.Text = "From Date:";
                    labelToDate.Text = "To Date:";
                    labelDateDescription.Text = "";
                }
                else
                {
                    labelFromDate.Text = "Search Timestamp:";
                    labelToDate.Text = "";
                    labelDateDescription.Text = "Will only look for log files that might have that timestamp.";
                }
            }
            else
            {
                dateTimeToFilter.Enabled = false;

                labelFromDate.Text = "Do not filter by Date.";
                labelToDate.Text = "";
                labelDateDescription.Text = "";
            }
        }

        #endregion

        #region UI Events

        private void ScanViewer_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void buttonScan_Click(object sender, EventArgs e)
        {
            try
            {
                if (!backgroundWorkerScan.IsBusy)
                {
                    if (!string.Equals(comboFileFitler.Text, comboFileFitler.SelectedValue))
                    {
                        if (!comboFileFitler.Items.Contains(comboFileFitler.Text))
                        {
                            if (comboFileFitler.Items.Count > 0)
                            {
                                comboFileFitler.Items.Insert(0, comboFileFitler.Text);
                            }
                            else
                            {
                                comboFileFitler.Items.Add(comboFileFitler.Text);
                            }
                        }
                    }

                    listMatchedFiles.Items.Clear();
                    buttonScan.Text = "&Stop Scan";

                    UpdateDefaultSettings();

                    backgroundWorkerScan.RunWorkerAsync();
                }
                else
                {
                    buttonScan.Text = "Stopping";
                    buttonScan.Enabled = false;
                    backgroundWorkerScan.CancelAsync();
                }
            }
            catch (Exception ex)
            {
                logMessage(string.Format("Unable to perform grep due to: {0}", ex.Message), Utility.MessageLevel.ERROR);
            }
        }

        private void dateTimeFromFilter_ValueChanged(object sender, EventArgs e)
        {
            setDateFillterType();
        }

        private void dateTimeToFilter_ValueChanged(object sender, EventArgs e)
        {
            setDateFillterType();
        }

        private void datePasteMenuItem_Click(object sender, EventArgs e)
        {
            DateTime date;

            DateTime.TryParse(Clipboard.GetText(), out date);
            if (date != null)
            {
                object source = contextMenuDate.SourceControl;

                if (source == dateTimeFromFilter )
                {
                    if (dateTimeFromFilter.Checked)
                    {
                        dateTimeFromFilter.Value = date;
                    }
                    else
                    {
                        logMessage("Unable to parse the date, from date is not enabled", Utility.MessageLevel.WARN);
                    }

                }
                else if (source == dateTimeToFilter)
                {
                    if (dateTimeToFilter.Checked)
                    {
                        dateTimeToFilter.Value = date;
                    }
                    else
                    {
                        logMessage("Unable to parse the date, to date is not enabled", Utility.MessageLevel.WARN);
                    }
                }
            }
            else
            {
                logMessage("Unable to parse the date", Utility.MessageLevel.WARN);
            }
        }

        private void nowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DateTime date = DateTime.Now;

            object source = contextMenuDate.SourceControl;

            if (source == dateTimeFromFilter)
            {
                if (dateTimeFromFilter.Checked)
                {
                    dateTimeFromFilter.Value = date;
                }
                else
                {
                    logMessage("Unable to set the current date, from date is not enabled", Utility.MessageLevel.WARN);
                }

            }
            else if (source == dateTimeToFilter)
            {
                if (dateTimeToFilter.Checked)
                {
                    dateTimeToFilter.Value = date;
                }
                else
                {
                    logMessage("Unable to set the current date, to date is not enabled", Utility.MessageLevel.WARN);
                }
            }
        }

        private void dateCopyMenuItem_Click(object sender, EventArgs e)
        {
            object source = contextMenuDate.SourceControl;
            if (source == dateTimeFromFilter)
            {
                string date = dateTimeFromFilter.Value.ToString();
                Clipboard.SetText(date, TextDataFormat.UnicodeText);
                logMessage(string.Format("Date copied: {0}", date), Utility.MessageLevel.INFO);
            }
            else if (source == dateTimeToFilter)
            {
                string date = dateTimeToFilter.Value.ToString();
                Clipboard.SetText(date, TextDataFormat.UnicodeText);
                logMessage(string.Format("Date copied: {0}", date), Utility.MessageLevel.INFO);
            }

        }

        private void listMatchedFiles_DoubleClick(object sender, EventArgs e)
        {
            OpenExternalEditor();
        }

        private void listMatchedFiles_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == listMatchedFilesColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (listMatchedFilesColumnSorter.Order == SortOrder.Ascending)
                {
                    listMatchedFilesColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    listMatchedFilesColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                listMatchedFilesColumnSorter.SortColumn = e.Column;
                listMatchedFilesColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.listMatchedFiles.Sort();
        }

        private void buttonAddPaths_Click(object sender, EventArgs e)
        {
            ScanSetting scanSetting = comboBoxRecentSearch.SelectedItem as ScanSetting;

            if (scanSetting == null)
            {
                foreach (ScanSetting searchScanSetting in comboBoxRecentSearch.Items)
                {
                    if (searchScanSetting.Name == comboBoxRecentSearch.Text)
                    {
                        scanSetting = searchScanSetting;
                        break;
                    }
                }

            }
            else
            {
                // if there is a selected setting, but the name has changed, make sure to clear it
                if (scanSetting.Name != comboBoxRecentSearch.Text)
                {
                    scanSetting = null;
                }
            }

            // if we are creating a new Scan Setting, initilize it here.
            if (scanSetting == null)
            {
                scanSetting = new ScanSetting();
            }

            StoreScanSetting(scanSetting);
        }


        private void buttonRemovePaths_Click(object sender, EventArgs e)
        {
            try
            {
                ScanSetting scanSetting = comboBoxRecentSearch.SelectedItem as ScanSetting;
                if (scanSetting != null)
                {
                    scanSetting.Remove();
                    comboBoxRecentSearch.Items.Remove(scanSetting);

                    NotifyLogMessage("The Scan Setting: " + scanSetting.Name + " was removed", Utility.MessageLevel.WARN);
                }
                else
                {
                    NotifyLogMessage("No Scan Setting selected.", Utility.MessageLevel.WARN);
                }
            }
            catch (Exception ex)
            {
                NotifyLogMessage("Unable to remove the scan settings: " + ex.Message, Utility.MessageLevel.ERROR);
            }
        }

        private void grepToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenGrepWindow();
        }

        private void buttonGrep_Click(object sender, EventArgs e)
        {
            OpenGrepWindow();
        }
        
        private void externalEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenExternalEditor();
        }

        private void openFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFolder();
        }

        private void internalEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // for each file, open either extenral editor
            foreach (ListViewItem listItem in listMatchedFiles.SelectedItems)
            {
                OpenStream(listItem);
            }
        }

        private void comboBoxRecentSearch_SelectedValueChanged(object sender, EventArgs e)
        {
            ScanSetting scanSetting = comboBoxRecentSearch.SelectedItem as ScanSetting;
            if (scanSetting != null)
            {
                LoadScanSetting(scanSetting);
            }
        }

        private void LoadScanSetting(ScanSetting scanSetting)
        {
            if (!scanSetting.Loaded)
            {
                scanSetting.Load();
            }

            comboBoxRecentSearch.Text = scanSetting.Name;

            textPaths.Text = string.Join<string>(Environment.NewLine, scanSetting.Paths);

            if (!string.IsNullOrEmpty(scanSetting.FileFilter))
            {
                comboFileFitler.Text = scanSetting.FileFilter;
            }

            if (scanSetting.FilterFromDate > DateTime.MinValue)
            {
                dateTimeFromFilter.Value = scanSetting.FilterFromDate;
                dateTimeFromFilter.Checked = true;
            }
            else
            {
                dateTimeFromFilter.Checked = false;
            }

            if (scanSetting.FilterToDate > DateTime.MinValue)
            {
                dateTimeToFilter.Value = scanSetting.FilterToDate;
                dateTimeToFilter.Checked = true;
            }
            else
            {
                dateTimeToFilter.Checked = false;
            }

            // just in case default to current time of both are not set
            if (!dateTimeFromFilter.Checked && !dateTimeToFilter.Checked)
            {
                dateTimeFromFilter.Value = DateTime.Now;
                dateTimeFromFilter.Checked = true;
            }
        }

        private void listMatchedFiles_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                foreach (ListViewItem item in listMatchedFiles.Items)
                {
                    item.Selected = true;
                }
            }
        }

        #endregion

    }
}
